package com.example.houseitemmanagebackend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.houseitemmanagebackend.entity.Items;
import com.example.houseitemmanagebackend.entity.Locations;
import com.example.houseitemmanagebackend.exception.BusinessException;
import com.example.houseitemmanagebackend.mapper.ItemMapper;
import com.example.houseitemmanagebackend.mapper.LocationMapper;
import com.example.houseitemmanagebackend.service.LocationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 位置服务实现类
 */
@Service
public class LocationServiceImpl implements LocationService {

    @Autowired
    private LocationMapper locationMapper;

    @Autowired
    private ItemMapper itemMapper;

    @Override
    @Cacheable(value = "locationList", key = "#userId")
    public List<Locations> getLocationList(Integer userId) {
        // 用户自定义位置
        LambdaQueryWrapper<Locations> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Locations::getUserId, userId);

        queryWrapper.orderByDesc(Locations::getCreatedAt);

        return locationMapper.selectList(queryWrapper);
    }

    @Override
    @Transactional
    @CacheEvict(value = "locationList", key = "#userId")
    public Integer addLocation(String name, Integer userId) {
        // 创建新位置
        Locations locations = new Locations();
        locations.setName(name);
        locations.setUserId(userId);
        locations.setIsSystem(0); // 非系统预设
        locations.setCreatedAt(LocalDateTime.now());
        locations.setUpdatedAt(LocalDateTime.now());

        locationMapper.insert(locations);

        return locations.getId();
    }

    @Override
    @Transactional
    @CacheEvict(value = "locationList", key = "#userId")
    public void updateLocation(Integer id, String name, Integer userId) {
        // 检查位置是否存在
        Locations locations = locationMapper.selectById(id);
        if (locations == null) {
            throw new BusinessException(404, "位置不存在");
        }

        // 检查新名称是否与其他位置重复
        LambdaQueryWrapper<Locations> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Locations::getName, name)
                .and(wrapper -> wrapper.eq(Locations::getUserId, userId).or().eq(Locations::getIsSystem, 1))
                .ne(Locations::getId, id);

        if (locationMapper.selectCount(queryWrapper) > 0) {
            throw new BusinessException(400, "位置名称已存在");
        }

        // 更新位置
        locations.setName(name);
        locations.setUpdatedAt(LocalDateTime.now());

        locationMapper.updateById(locations);
    }

    @Override
    @Transactional
    @CacheEvict(value = "locationList", key = "#userId")
    public void deleteLocation(Integer id, Integer userId) {
        // 检查位置是否存在
        Locations locations = locationMapper.selectById(id);
        if (locations == null) {
            throw new BusinessException(404, "位置不存在");
        }

        // 检查是否有权限操作（只能删除自己创建的非系统位置）
        if (locations.getIsSystem() == 1 || !locations.getUserId().equals(userId)) {
            throw new BusinessException(403, "无权限操作此位置");
        }

        // 检查是否有物品使用此位置
        LambdaQueryWrapper<Items> itemQueryWrapper = new LambdaQueryWrapper<>();
        itemQueryWrapper.eq(Items::getLocationId, id);

        long count = itemMapper.selectCount(itemQueryWrapper);
        if (count > 0) {
            throw new BusinessException(400, "该位置下存在物品，无法删除");
        }

        // 删除位置
        locationMapper.deleteById(id);
    }
}